//
//  FriendListWindowController.m
//  MacDevTest
//
//  Created by 夏利兵 on 2020/8/13.
//  Copyright © 2020 com.lbx. All rights reserved.
//

#import "FriendListWindowController.h"
#import "CustomRowView.h"
#import "FriendListView.h"
#import "JJScroller.h"
#import <Masonry/Masonry.h>

@interface FriendListWindowController ()<NSTabViewDelegate,NSTableViewDataSource>
@property (nonatomic,strong)  NSTableView *tableView;

@property (nonatomic, strong) NSMutableArray<NSArray*> *listDatas;

@property (nonatomic, assign) NSInteger listCount;

@property (nonatomic, copy) NSString *lastText;

@end

@implementation FriendListWindowController


- (void)windowDidLoad {
    [super windowDidLoad];
    
    NSArray* array1 = @[@"col1_field1",@"col1_field2"];
    NSArray* array2 = @[@"col2_field1",@"col2_field2"];
    
    self.listCount = 2;

    self.listDatas =  [NSMutableArray arrayWithObjects:array2,array1, nil];
    

    NSScrollView * scrollView    = [[NSScrollView alloc] init];
    scrollView.borderType = NSNoBorder;
    
    //自定义滚动条，没有背景色，静止时，自动隐藏
    scrollView.verticalScroller = [[JJScroller alloc]init];
    scrollView.hasVerticalScroller  = YES;
    NSRect frame = self.window.contentView.bounds;
    frame.size.width = 200;
    scrollView.frame = frame;
    [self.window.contentView addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.equalTo(self.window.contentView);
        make.top.equalTo(self.window.contentView);
        make.width.mas_equalTo(200);
    }];
    
    self.tableView = [[NSTableView alloc]initWithFrame:self.window.contentView.bounds];
    NSTableColumn * column = [[NSTableColumn alloc]initWithIdentifier:@"col1"];
    column.title = @"col1";
    column.minWidth = 200;
    column.maxWidth = 200;
    column.headerCell = [[NSTableHeaderCell alloc]initTextCell:@"11"];
    column.headerCell.backgroundColor = [NSColor clearColor];
    [_tableView addTableColumn:column];

    //tableview单列模拟iOS封装，通过继承NSTableView，监听鼠标事件，返回相关事件通知
//    _tableView rowAtPoint:<#(NSPoint)#>
    
    //隐藏列表头 列的名称
    [_tableView setHeaderView:nil];
    
    
    scrollView.contentView.documentView = _tableView;

    //Assigning to 'id<NSTableViewDelegate> _Nullable' from incompatible type 'NormalTableView *const __strong'
    _tableView.delegate = (id)self;
    _tableView.dataSource = self;
    [_tableView reloadData];
    
    [_tableView reloadData];
}
- (IBAction)addTest:(id)sender {
    
    self.listCount++;
    
     NSInteger selectedRow = [self.tableView selectedRow];

    [self.tableView reloadData];
    
    if ( selectedRow >=0 && selectedRow <= (self.listCount - 1) ) {
           [self.tableView selectRowIndexes:[[NSIndexSet alloc]initWithIndex:selectedRow] byExtendingSelection:NO];
         //    [self.tableView selectRowIndexes:selectedSet byExtendingSelection:false];
             
     }
}

- (IBAction)subTest:(id)sender {
    
//    NSIndexSet *selectedSet = [self.tableView selectedRowIndexes];
    
    // <0 表示没有选中项
   NSInteger selectedRow = [self.tableView selectedRow];

    
    self.listCount--;
    [self.tableView reloadData];
    
    //恢复指定选中项
    if ( selectedRow >=0 && selectedRow <= (self.listCount - 1) ) {
          [self.tableView selectRowIndexes:[[NSIndexSet alloc]initWithIndex:selectedRow] byExtendingSelection:NO];
    }
    
    
    if (self.listCount <= 0) {
        return;
    }
    
    
    //获取指定行视图，进行局部刷新
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新界面
            FriendListView *listView = (FriendListView*)[self.tableView viewAtColumn:0 row:self.listCount-1 makeIfNecessary:NO];
               
               if (listView) {
                   NSLog(@"listView title:%@",listView.userNickName.stringValue);
                   
                   //不用刷新，直接修改搞定
                   listView.userNickName.stringValue = @"局部修改测试";

                   //或者利用绑定的数据局部刷新搞定
//                   self.lastText = @"测试局部刷新";
//                   NSIndexSet *columnIndexs = [[NSIndexSet alloc]initWithIndex:0];
//                   NSIndexSet *rowIndexs = [[NSIndexSet alloc]initWithIndex:self.listCount-1];
//                   [self.tableView reloadDataForRowIndexes:rowIndexs columnIndexes:columnIndexs];
               }
        });
    });
    
    //增加或删除行 局部刷新无效，某个row信息有变化，可以通过获取到view直接修改，或者绑定的数据修改，局部刷新即可
//    NSIndexSet *columnIndexs = [[NSIndexSet alloc]initWithIndex:0];
//    NSIndexSet *rowIndexs = [[NSIndexSet alloc]initWithIndex:self.listCount-1];
//    [self.tableView reloadDataForRowIndexes:rowIndexs columnIndexes:columnIndexs];
}

#pragma mark- delegate

//  - （BOOL）validateProposedFirstResponder：（NSResponder *）responder forEvent：（NSEvent *） event
// {
// //这允许用户点击单元格中的控件，首先必须选择单元格行
// return YES;
//}

- (BOOL)validateProposedFirstResponder:(NSResponder *)responder forEvent:(NSEvent *)event
{
    return YES;
}
 

- (BOOL)tabView:(NSTabView *)tabView shouldSelectTabViewItem:(nullable NSTabViewItem *)tabViewItem
{
    return YES;
}

- (void)tabView:(NSTabView *)tabView willSelectTabViewItem:(nullable NSTabViewItem *)tabViewItem
{
    NSLog(@"willSelectTabViewItem");
}

- (void)tabView:(NSTabView *)tabView didSelectTabViewItem:(nullable NSTabViewItem *)tabViewItem
{
    NSLog(@"didSelectTabViewItem :%@",tabViewItem.identifier);
}

- (void)tabViewDidChangeNumberOfTabViewItems:(NSTabView *)tabView
{
    NSLog(@"tabViewDidChangeNumberOfTabViewItems");
}

#pragma mark - NSTableViewDataSource
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
//    return self.listDatas.count;
    
    return self.listCount;
}

// 设置行高
- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row{
    return 60;
}



- (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row
{
    //修改选中颜色
    CustomRowView *rowView = [[CustomRowView alloc] init];
    return rowView;
}

//view-based模式(基于视图)

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    
//    NSView *view = [[NSView alloc]initWithFrame:NSMakeRect(0, 0, 300, 40)];
//    view.wantsLayer = YES;
//    view.layer.backgroundColor = [NSColor blackColor].CGColor;
//    return view;
    
//    NSArray* array = self.listDatas[row];

    
    FriendListView *fView = [[FriendListView alloc]initWithFrame:NSMakeRect(0, 0, 220, 40)];
    
//    fView.userImageView.image = [NSImage imageNamed:NSImageNameUser];
    
    fView.userImageView.image = [NSImage imageNamed:@"personalImg"];
    

//    fView.userNickName.stringValue = array.firstObject;
    fView.userNickName.stringValue = [NSString stringWithFormat:@"朋友昵称:%ld",(long)row];
    
    
    fView.detailInfo.stringValue = [NSString stringWithFormat:@"detaininfo"];
    
    
    if (row == self.listCount -1 && _lastText) {
        fView.detailInfo.stringValue = _lastText;
    }

    return fView;
}

- (void)didCloseView:(NSInteger)row identifer:(NSString*)identifer view:(FriendListView*)view
{
    
}


@end
